package com.kfm.servlet.day04;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cookie")
public class CookieServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建一个 cookie 对象
        Cookie cookie = new Cookie("name", "kfm");
        cookie.setPath("/"); // 设置 cookie 的有效路径
        // 默认有效时间是 -1，关闭浏览器就失效
        cookie.setMaxAge(60 * 60 * 24); // 设置 cookie 的有效时间

        Cookie addr = new Cookie("addr", "西安");

        // 发送到客户端
        resp.addCookie(cookie);
        resp.addCookie(addr);

        // 客户端响应 设置cookie成功
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write("设置cookie成功");
    }
}
